<template>
  <view class="posterWrapper">
    <tki-qrcode :showLoading="false" class="qrImg hideQrImg" ref="qrcode" :val="qrcodeUrl" :onval="true" :size="128" :loadMake="true" @result="qrR"/>
    <view class="layer" @click="closePoster"></view>
    <view class="poster">
      <canvas style="height: 100%;width: 100%;" v-if="!posterImg" canvas-id="myCanvas"></canvas>
      <image :src="posterImg" v-else class="poster"></image>
    </view>
  </view>
</template>
<script>
import tkiQrcode from "@/components/tki-qrcode/tki-qrcode.vue"
export default {
  components: {
    tkiQrcode
  },
  props:{
    goodObj: {
      type: Object,
      default: () => {}
    }
  },
  data () {
    return {
      userInfo: '',
      posterImg: '',
      qrcodeUrl: ''
    }
  },
  watch: {
    goodObj: {
      handler(newValue, oldValue) {
        if (newValue) {
          this.qrcodeUrl = newValue.url;
        }
      },
      immediate: true
    }
  },
  onShow() {
    console.log(this.goodObj, 'goodObj is')
  },
  methods: {
    closePoster () {
      this.$emit('closePoster', '');
    },
    creatQrcode() {
      this.$refs.qrcode._makeCode()
    },
    qrR (path) {
      if (path == '') {
        uni.showToast({
          title: '生成失败，请重试',
          icon: 'none'
        });
        return;
      }
      wx.showLoading({
        title: '分享图片生成中...',
        icon: 'loading',
        duration: 1000
      });
      // let _self = this;
      // uni.getImageInfo({
      //   // src: _self.goodObj.images[0] + '?' + new Date().getTime(),
      //   src: _self.goodObj.images[0],
      //   success(res) {
      //     setTimeout(() => {
      //       _self.drawCanvas(ctx, res.path, path)
      //     }, 1000);
      //   }
      // })
      setTimeout(() => {
        this.drawCanvas(this.goodObj.images[0], path)
      }, 1000);
    },
    drawCanvas (mainImg, path) {
      let ctx = uni.createCanvasContext('myCanvas');
      ctx.setFillStyle('#FFFFFF')
      ctx.fillRect(0,0,uni.upx2px(510),uni.upx2px(752))
      
      // ctx canvasId mainImg: 分享当前商品的图片 path: 二维码的地址
      ctx.drawImage(mainImg, 0, 0, uni.upx2px(510), uni.upx2px(510))
      ctx.setFontSize(uni.upx2px(28))
      ctx.setFillStyle('#000000')
      // this.drawText(ctx, this.goodObj.name, uni.upx2px(20), uni.upx2px(552), uni.upx2px(40), uni.upx2px(300), 2)
      // 判断内容是否可以一行绘制完毕
      var drawTxt = ''; // 当前绘制的内容
      var drawLine = 1; // 第几行开始绘制    
      var drawIndex = 0; // 当前绘制内容的索引 
      var drawX = uni.upx2px(20);
      var drawY = uni.upx2px(552);
      if(ctx.measureText(this.goodObj.name).width <= uni.upx2px(300)) {
        ctx.fillText(this.goodObj.name, drawX, drawY);    
      } else {        
        for (var i = 0; i < this.goodObj.name.length; i++) {                
          drawTxt += this.goodObj.name[i];                
          if (ctx.measureText(drawTxt).width >= uni.upx2px(300)) {                   
            if (drawLine >= 2) {                       
              ctx.fillText(this.goodObj.name.substring(drawIndex, i) + '..', drawX, drawY);                        
              break;                   
            } else {                       
              ctx.fillText(this.goodObj.name.substring(drawIndex, i + 1), drawX, drawY);                    
              drawIndex = i + 1;
              drawLine += 1;
              drawY += uni.upx2px(40);
              drawTxt = '';           
            }                           
          } else {                              
            // 内容绘制完毕，但是剩下的内容宽度不到300                    
            if (i === this.goodObj.name.length - 1) {                        
              ctx.fillText(this.goodObj.name.substring(drawIndex), drawX, drawY);                    
            }
          }            
        }
      }
      ctx.setFontSize(uni.upx2px(20))
      ctx.setFillStyle('#000000')
      ctx.fillText(this.goodObj._userName + '推荐', uni.upx2px(86), uni.upx2px(646))
      // // 绘制价格
      ctx.setFontSize(uni.upx2px(32))
      ctx.setFillStyle('#FC4A5B')
      ctx.fillText('￥' + this.goodObj.price, uni.upx2px(20), uni.upx2px(718))
      ctx.setFontSize(uni.upx2px(24))
      ctx.setFillStyle('#999')
      ctx.fillText('￥' + this.goodObj.marketPrice, uni.upx2px(156), uni.upx2px(718))
      // ctx.setLineWidth(1)
      // ctx.beginPath()
      ctx.moveTo(uni.upx2px(156), uni.upx2px(710))
      ctx.lineTo(uni.upx2px(240), uni.upx2px(710))
      ctx.setStrokeStyle('#999')
      ctx.stroke()
      // // 二维码的位置
      ctx.drawImage(path, uni.upx2px(362), uni.upx2px(562), uni.upx2px(128), uni.upx2px(128))
      // // 绘制圆形头像
      ctx.arc(uni.upx2px(48), uni.upx2px(640), uni.upx2px(28), 0, 2 * Math.PI)
      ctx.clip()
      this.goodObj._href = this.goodObj._href?this.goodObj._href:"https://zy-image.oss-cn-hangzhou.aliyuncs.com/avatar_default.jpg";
      ctx.drawImage(this.goodObj._href, uni.upx2px(20), uni.upx2px(612), uni.upx2px(56), uni.upx2px(56))
      // ctx.restore()
      let _self = this;
      ctx.draw(false, () => {
        uni.canvasToTempFilePath({
          canvasId: 'myCanvas',
          success (res) {
            uni.hideLoading();
            setTimeout(() => {
              _self.posterImg = res.tempFilePath
            },2000)
          },
          fail (res) {
            uni.hideLoading();
            uni.showToast({
              title: '生成海报失败',
              icon: 'none'
            })
          }
        },_self)
      })
    },
    // 1、canvas对象，2、文本 3、距离左侧的距离 4、距离顶部的距离 5、6、文本的宽度
    drawText (ctx, content, drawX, drawY, lineHeight, lineMaxWidth, lineNum) {
      var drawTxt = ''; // 当前绘制的内容    
      var drawLine = 1; // 第几行开始绘制    
      var drawIndex = 0; // 当前绘制内容的索引    
      // 判断内容是否可以一行绘制完毕    
      if(ctx.measureText(content).width <= lineMaxWidth) {        
        ctx.fillText(content.substring(drawIndex, i), drawX, drawY);    
      } else {        
        for (var i = 0; i < content.length; i++) {                
          drawTxt += content[i];                
          if (ctx.measureText(drawTxt).width >= lineMaxWidth) {                   
            if (drawLine >= lineNum) {                       
              ctx.fillText(content.substring(drawIndex, i) + '..', drawX, drawY);                        
              break;                   
            } else {                       
              ctx.fillText(content.substring(drawIndex, i + 1), drawX, drawY);                    
              drawIndex = i + 1;
              drawLine += 1;
              drawY += lineHeight;
              drawTxt = '';           
            }                           
          } else {                              
            // 内容绘制完毕，但是剩下的内容宽度不到lineMaxWidth                    
            if (i === content.length - 1) {                        
              ctx.fillText(content.substring(drawIndex), drawX, drawY);                    
            }
          }            
        }
      }
    },
    // saveFile () {
    //   uni.saveImageToPhotosAlbum({
    //     filePath: this.posterImg,
    //     success() {
    //       uni.showToast({
    //         title: '图片保存成功！'
    //       })
    //     },
    //     fail () {
    //       uni.showToast({
    //         title: '图片保存失败！'
    //       })
    //     }
    //   })
    // }
  }
  
}
</script>
<style scoped lang="scss">
.hideQrImg {
  position: absolute;
  left: -140rpx;
  bottom: -110rpx;
}
.flt-fr {
  float: right;
}
.flt-fl {
  float: left;
}
.layer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 99;
  background: rgba(0,0,0,.5);
}
.posterWrapper {
  background-color: #FFFFFF;
  .poster{
    position: fixed;
    z-index: 999;
    top:50%;
    left:50%;
    margin-left: -255rpx;
    margin-top: -370rpx;
    width: 510rpx;
    height: 752rpx;
    background-color: #FFFFFF;
    border-radius: 12rpx;
    .mainImg{
      width: 510rpx;
      height: 510rpx;
      display: block;
      // margin-bottom: 20rpx;
    }
    .objDes{
      background-color: #FFFFFF;
      padding: 20rpx;
      overflow: hidden;
      .title{
        font-size: 28rpx;
        line-height: 40rpx;
        width: 300rpx;
      }
      .mrb10{
         margin: 10rpx 0;
      }     
      .headImg{
        width: 56rpx;
        height: 56rpx;
        margin-right: 10rpx;
       }
       .price{
         font-size: 32rpx;
         color: #FC4A5B;
       }
       .orgPrice{
         color: #999999;
         text-decoration:line-through ;
         margin-left: 12rpx;
       }
       .qrImg{
         margin-top: 36rpx;
         border: 1px solid red;
       }
    }
   }
} 
</style>